package gozero

import (
	"reflect"
	"strings"
)

const TAG_FRAME = "zero"

func snakecase(s string) string {
	s = strings.Replace(s, "ID", "Id", -1)
	s = strings.Replace(s, "FK", "Fk", -1)
	data := make([]byte, 0, len(s)*2)
	ok := false
	for i := 0; i < len(s); i++ {
		d := s[i]
		if i > 0 && d >= 'A' && d <= 'Z' && ok {
			data = append(data, '_')
		}
		if d != '_' {
			ok = true
		}
		data = append(data, d)
	}
	return strings.ToLower(string(data[:]))

}

func camelcase(s string) string {
	s = strings.Replace(s, "_id", "ID", -1)
	data := make([]byte, 0, len(s))
	j := false
	k := false
	num := len(s) - 1
	for i := 0; i <= num; i++ {
		d := s[i]
		if !k && d >= 'A' && d <= 'Z' {
			k = true
		}
		if d >= 'a' && d <= 'z' && (j || !k) {
			d = d - 32
			j = false
			k = true
		}
		if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
			j = true
			continue
		}
		data = append(data, d)
	}
	return string(data[:])
}

func tag(tag reflect.StructTag, key string, defaultKey string) string {
	var s string
	if s = tag.Get(TAG_FRAME); s == "" {
		return defaultKey
	}
	semicolon := strings.Split(s, ";")
	for _, seg := range semicolon {
		colon := strings.Split(seg, ":")
		if colon[0] == key {
			return colon[1]
		}
	}
	return defaultKey
}

func isPrimaryKey(tag reflect.StructTag) bool {
	var s string
	if s = tag.Get(TAG_FRAME); s == "" {
		return false
	}
	semicolon := strings.Split(s, ";")
	for _, seg := range semicolon {
		if seg == TAG_PRIMARY_KEY {
			return true
		}
	}
	return false
}
